import { createRouter, createWebHashHistory } from 'vue-router'
import routes from './routes'
import { localGet } from '../utils/auth.js'

// history模式不连后端的话打包静态显示不了
// const router = createRouter({
//   history: createWebHistory('/viteApp/'), // history模式使用HTML5模式
//   routes
// })

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  // 让页面回到顶部
  // chrome
  document.body.scrollTop = 0
  // firefox
  document.documentElement.scrollTop = 0
  // safari
  window.pageYOffset = 0
  if (to.meta.needLogin) {
    if (localGet('STEM_TOKEN')) {
      next()
    } else {
      next({ path: '/login' })
    }
  } else {
    // 路由白名单，不检验token直接放行
    next()
  }
})

export default router
